package com.example.sensormanagerdemo;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {
	private ImageView iv_compass;
	private TextView tv_degree;
	private TextView tv_orientation;
	private SensorManager manager;
	private float startDegree = 0f;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		iv_compass = (ImageView) findViewById(R.id.iv_compass);
		tv_degree = (TextView) findViewById(R.id.tv_degree);
		tv_orientation = (TextView) findViewById(R.id.tv_orientation);

		// 获得传感器管理器
		manager = (SensorManager) getSystemService(SENSOR_SERVICE);

	}

	@Override
	protected void onResume() {
		super.onResume();
		// 为方向传感器注册监听器
		manager.registerListener(listener,
				manager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);

	}

	private SensorEventListener listener = new SensorEventListener() {

		@Override
		public void onSensorChanged(SensorEvent event) {
			if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
				// 获取当前传感器获取到的角度
				float degree = -event.values[0];
				setOrientation((int) event.values[0]);

				tv_degree.setText((int) event.values[0] + "");
				// 通过补间动画旋转角度 从上次的角度旋转
				RotateAnimation ra = new RotateAnimation(startDegree, degree,
						Animation.RELATIVE_TO_SELF, 0.5f,
						Animation.RELATIVE_TO_SELF, 0.5f);
				ra.setDuration(100);
				iv_compass.startAnimation(ra);
				// 记录当前旋转后的角度
				startDegree = degree;
			}
		}

		private void setOrientation(int degree) {

			if (degree < 30) {
				tv_orientation.setText("北");
			} else if (degree < 60) {
				tv_orientation.setText("东北");
			} else if (degree < 120) {
				tv_orientation.setText("东");
			} else if (degree < 150) {
				tv_orientation.setText("东南");
			} else if (degree < 210) {
				tv_orientation.setText("南");
			} else if (degree < 240) {
				tv_orientation.setText("西南");
			} else if (degree < 300) {
				tv_orientation.setText("西");
			} else if (degree < 330) {
				tv_orientation.setText("西北");
			} else {
				tv_orientation.setText("北");
			}

		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}
	};

	@Override
	protected void onStop() {
		// 为传感器注销监听器
		manager.unregisterListener(listener);
		super.onStop();
	}
}
